package com.gjx.leetcode;
//92. 反转链表 II
//
//反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
//
//说明:
//1 ≤ m ≤ n ≤ 链表长度。
//
//示例:
//
//输入: 1->2->3->4->5->NULL, m = 2, n = 4
//输出: 1->4->3->2->5->NULL

public class Solution092 {
	public ListNode reverseBetween(ListNode head, int m, int n) {
        
		if (head == null || m == n) {
			return head;
		}
		
		ListNode dummy = new ListNode(0);
		dummy.next = head;
		
		ListNode dummyPre = dummy;
		
		for (int i=1; i<m; i++) {
			dummyPre = dummyPre.next;
		}
		
		ListNode pre = dummyPre.next;
		ListNode cur = pre.next;
		ListNode nxt = cur.next;
		
		for (int i=m; i<n; i++) {
			
			cur.next = pre;
			pre = cur;
			cur = nxt;
			if (nxt != null) {
				nxt = nxt.next;
			} else {
				break;
			}
			
		}
		
		dummyPre.next.next = cur;
		dummyPre.next = pre;
		
		return dummy.next;
    }
}
